<template>
  <!-- 上传文件 -->
  <div>
    <el-upload
      ref="upload"
      :accept="fileType.join(',')"
      :limit="1"
      :headers="upload.headers"
      :action="upload.url"
      :disabled="upload.isUploading"
      :before-upload="beforeUpload"
      :on-progress="handleFileProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <el-button type="success" size="mini" @click="submitUpload"
      >上传到服务器</el-button
    >
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "Upload",
  data() {
    return {
      fileType: [".PDF", ".pdf", ".word"],
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传地址
        url: "https://jsonplaceholder.typicode.com/posts/",
        // 是否更新已经存在的用户数据
        isUploading: false,
      },
    };
  },
  methods: {
    // 文件上传中处理
    handleFileProgress() {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess() {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    // 提交上传文件
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      const isXlsx = file.type === "application/vnd.ms-excel";
      if (!isXlsx) {
        this.$message.error("上传文件只能是 PDF 或 word 格式");
      }
      return isXlsx;
    },
  },
};
</script>
